package com.example.shw.download

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.ProgressBar
import com.example.shw.R
import java.lang.ref.WeakReference
import java.util.*

class DownActivity : AppCompatActivity(){
    private lateinit var url: EditText
    private lateinit var target: EditText
    private lateinit var downBn: Button
    private lateinit var bar: ProgressBar
    private lateinit var downUtil: DownUtil
    class MyHandler(private var downActivity: WeakReference<DownActivity>) : Handler(){
        override fun handleMessage(msg: Message) {
            if (msg.what == 0x123){
                downActivity.get()?.bar?.progress = msg.arg1
            }
        }
    }
    private val handler = MyHandler(WeakReference(this))
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_download)
        url = findViewById(R.id.url)
        target = findViewById(R.id.target)
        downBn = findViewById(R.id.down)
        bar = findViewById(R.id.bar01)
        requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 0x456)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        if (requestCode == 0x456 && grantResults != null
            && grantResults.size == 1
            && grantResults[0] == PackageManager.PERMISSION_GRANTED)
        {
            downBn.setOnClickListener {
                Log.d("12345",url.text.toString())
                downUtil = DownUtil(url.text.toString(), target.text.toString(), 6)
                object : Thread(){
                    override fun run() {
                        downUtil.download()

                        val timer = Timer()
                        timer.schedule(object : TimerTask(){
                            override fun run() {
                                val completeRate = downUtil.completeRate
                                println(completeRate)
                                val msg = Message.obtain()
                                msg.what = 0x123
                                msg.arg1 = (completeRate * 100).toInt()
                                handler.sendMessage(msg)
                                if (completeRate >= 1)
                                {
                                    timer.cancel()
                                }
                            }
                        }, 0, 100)
                    }
                }.start()
            }
        }
    }
}